package simpleim

import (
	"context"
	"encoding/json"
	"github.com/IBM/sarama"
	"log"
	"strconv"
)

/*
IMService im后端服务
*/
type IMService struct {
	producer sarama.SyncProducer
}

// handle 处理消息
func (svc *IMService) handle(ctx context.Context, uid int64, msg Message) error {
	// 这里就是业务的大头
	// 可以做消息的审核、数据的同步搜索、消息记录的存储
	members := svc.findMembers(msg.Cid)
	for _, m := range members {
		// 需要去除掉自己
		if m == uid {
			continue
		}
		// 发布消息
		event, err := json.Marshal(Event{Msg: msg, Receiver: m})
		if err != nil {
			// 记录日志
			log.Printf("消息序列化失败:%v", err)
			continue
		}
		_, _, err = svc.producer.SendMessage(&sarama.ProducerMessage{
			Topic: EventName,
			Key:   sarama.StringEncoder(strconv.FormatInt(m, 10)),
			Value: sarama.ByteEncoder(event),
		})
		log.Printf("kafka发送消息:%v, err: %v", string(event), err)
		if err != nil {
			// 记录日志
			log.Printf("消息发布失败:%v", err)
		}
	}
	return nil
}

// findMembers 找到群组成员
func (svc *IMService) findMembers(cid string) []int64 {
	// TODO：需要换成实际的群组人员
	// 这里mock返回固定的
	return []int64{1, 2, 3}
}
